import nuke 
import os 
import shutil

def get_project_settings():
    """获取Nuke项目设置信息"""
    root = nuke.root()
    

    fps = root['fps'].value()
    start_frame = int(root['first_frame'].value())
    end_frame = int(root['last_frame'].value())


    format_node = root.format()
    width = format_node.width()
    height = format_node.height()
    pixel_aspect = format_node.pixelAspect()
    
    return {
        'fps': fps,
        'start_frame': start_frame,
        'end_frame': end_frame,
        'width': width,
        'height': height,
        'pixel_aspect': pixel_aspect,
        'format_name': format_node.name()
    }


def copy_file_efficiently(source_path, destination_path):
    try:
        shutil.copy2(source_path, destination_path)
    except IOError as e:
        return False
    return True


def add_losed_frame():
    project_info = get_project_settings()
    start_frame = project_info['start_frame']
    end_frame = project_info['end_frame']
    width = project_info['width']
    height = project_info['height']
    exr_file = f"T:\\L_Tools\\Nuke\\blackexr\\{width}x{height}.exr"
    if not os.path.exists(exr_file):
        print(f"exr文件不存在{exr_file}")
        return
    
    read_nodes = [node for node in nuke.allNodes() if node.Class() == "Read"]
    if not read_nodes:
        nuke.message("场景中没有Read节点")
        return
    frame_list = [i for i in range(start_frame,end_frame+1)]
    

    print('开始处理缺失帧')
    for read_node in read_nodes:
        file_path = read_node['file'].value()
        for frame in frame_list:
            tmp_file = file_path.replace("%04d",f"{frame:04d}")
            if not os.path.exists(tmp_file):
                print(f"文件不存在{tmp_file}--开始复制")
                if copy_file_efficiently(exr_file,tmp_file):
                    print(f"文件复制成功: {exr_file} -> {tmp_file}".format(exr_file=exr_file, tmp_file=tmp_file))
        read_node['reload'].execute()


if __name__ == '__main__':
    add_losed_frame()